package woda.ink.controller.download;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.multipart.MultipartFile;
import woda.ink.entity.fileEntity;
import woda.ink.entity.loginEntity;
import woda.ink.mapper.Commom;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;

import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE;

/**
 * program: CaseManager
 * package: com.longyiqun.cm.controller.download
 * author: 龙轶群
 * create: 2018-04-18 13:48
 **/

@RestController
@RequestMapping("/download")
public class DownloadRestControllerImpl {

    @Autowired
    private ServletContext servletContext;
    @Autowired
    private Commom commom;
    // 可以下载各种TYPE的资源 TIPS: APPLICATION_OCTET_STREAM_VALUE
    @RequestMapping(value = "/GetResource", method = RequestMethod.GET, produces = APPLICATION_OCTET_STREAM_VALUE)
    public void downResource(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileName ,@RequestParam String username) throws ServletException, IOException {
        String type = fileName.split("_")[0];
        if ("未登陆".contains(username)){
            fileEntity fileEntity = commom.EditSourceMapper("select * from plateform_file where fileName = '"+fileName+"' and eStatus = 1 and type like '%"+ type+"%' limit 1");
            String downloadTime = fileEntity.getDownCount();

            downloadTime = Integer.toString(Integer.parseInt(downloadTime)+1);

            int result = commom.UpdateSql("update plateform_file set downCount = "+downloadTime+" where sourseID = "+fileEntity.getSourseID());
        }else {
            //下载统计
            fileEntity fileEntity = commom.EditSourceMapper("select * from plateform_file where fileName = '"+fileName+"' and eStatus = 1 and type like '%"+ type+"%' limit 1");
            String downloadTime = fileEntity.getDownCount();
            downloadTime = Integer.toString(Integer.parseInt(downloadTime)+1);
            int result = commom.UpdateSql("update plateform_file set downCount = "+downloadTime+" where sourseID = "+fileEntity.getSourseID());
            //插入下载记录
            loginEntity loginEntity = commom.EditEmployeeMapper("select * from plateform_Employee where loginName = '"+username+"' and eStatus = 1 limit 1");
            int s = commom.InsertSql("insert into plateform_Record (type,employeeID) value ('"+type+"'"  +","+loginEntity.getEmployeeID()+  ")");

        }

        try {

            MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName);

            // FOR DEBUG
            System.out.println("fileName: " + fileName);
            System.out.println("mediaType: " + mediaType);

            response.setContentType(mediaType.getType());
           File file = new File("/home/jion/SourceManage/static/file/" +fileName);
//            File file = new File("/E:/ProjectManage/File/" +fileName);

            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);

            response.setContentLength((int) file.length());

            BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream outStream = new BufferedOutputStream(response.getOutputStream());

            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }

            outStream.flush();
            inStream.close();


        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
    }


    //上传资源
    @RequestMapping(value="/uploadAllFile")
    public String uploadByJJ(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception {
        //如果文件不为空，写入上传路径
        String Name = request.getParameter("person");
        String explain = "无";
        String title = request.getParameter("title");
        String type = request.getParameter("type2");
//        String type = "Article";
        String link = request.getParameter("link");
//        type = commom.count("select type from plateform_typeConf where name = '"+type+"'");
        fileEntity bk = new fileEntity();
        bk.setLeader(Name);
        bk.setType(type);
        bk.setFileExplain(explain);
        bk.setTitle(title);
        bk.setLink(link);

        System.out.println(type);
        if (type.contains("Article")){
            long stemptime = System.currentTimeMillis();
            String time =  String.valueOf(stemptime/1000);
            time = time.substring(7,9);
            String filename = type+"_"+time+file.getOriginalFilename();
            bk.setFileName(filename);
            commom.InsertResourse(bk);
            return "文章链接已保存";
        }
        if(!file.isEmpty()) {
            String path="" ;
            try {
                path = ResourceUtils.getURL("").getPath();
                System.out.println(path);
                 path= path +"static/file/";
                //path= path +"file/"; //windows下
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //上传文件名
            System.out.println(path);
            SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
            long stemptime = System.currentTimeMillis();
            String time =  String.valueOf(stemptime/1000);
            time = time.substring(7,9);
            String filename = type+"_"+time+file.getOriginalFilename();
            File NewFile = new File(path + File.separator + filename);
            //保存上传文件
            file.transferTo(NewFile);
            //记录写入数据库
            bk.setUrl(path);//文件路径
            bk.setFileName(filename);
            bk.setLink("http://192.168.200.41:8099/download/GetResource?"+filename);//下载链接
            int result = commom.InsertResourse(bk);
            if (result < 1){
                return "写入数据库失败";
            }
            return "小主资源上传成功";
        }else {
            return  "小主资源上传失败了";
        }
    }

}
